
import React, { useState, useEffect, useRef } from "react";
import Common from "@/components/common/index"
import { Button, Form, Input, Table, Pagination, Popconfirm, Select, DatePicker, Typography, Upload } from 'antd';
import { SearchOutlined, ReloadOutlined, CloudUploadOutlined, PlusOutlined, DownloadOutlined } from '@ant-design/icons';
import type { TableColumnsType, PaginationProps, UploadProps } from 'antd';
import { allKind, getNeedPlan, deleteMonth, addMonth, viewMonth, updateMonth } from "@/common/api"
import AddEdit from "./addEdit"
import dayjs from 'dayjs';


const Month: React.FC = () => {
    useEffect(() => {
        getkind()
        getData()
    }, []);
    const [form] = Form.useForm();
    const [loadings, setLoadings] = useState<boolean>(false);
    const [kindData, setKindData] = useState<any[]>([]);
    const [tableData, setTableData] = useState<any[]>([]);
    const onFinish = () => {
        pageNumRef.current = 1;
        setCurrent(1)
        getData()
    };
    const getkind = () => {
        allKind().then((res: any) => {
            if (res.success) {
                let data = res.data.map((i: any) => {
                    return {
                        label: i,
                        value: i
                    }
                })
                setKindData(data)
            }
        })
    }
    const props: UploadProps = {
        name: 'file',
        action: () => {
            if (process.env.NODE_ENV == "development") {
                return "http://192.168.10.87:8611/api/needPlan/import";
            } else {
                const host = window.location.protocol + "//" + window.location.host;
                return `${host}/api/needPlan/import`;
            }
        },
        headers: {},
        onChange(info) {
            if (info.file.status !== 'uploading') {

            }
            if (info.file.status === 'done') {
                if (info.file.response.success) {
                    $message.success(info.file.response.message);
                } else {
                    $message.error(info.file.response.message);
                }
            } else if (info.file.status === 'error') {
                $message.error('导入失败');
            }
        },
    };
    const download = () => {
        if (process.env.NODE_ENV == "development") {
            window.location.href = `http://192.168.10.87:8611/api/needPlan/template`;
        } else {
            const host = window.location.protocol + "//" + window.location.host;
            window.location.href = `${host}/api/needPlan/template`;
        }
    }
    const getTop = () => {
        return <Form
            layout="inline"
            form={form}
            onFinish={onFinish}
            autoComplete="off"
        >
            <Form.Item name="needYearMonth" label="需求年月 :" style={{ marginBottom: '10px' }}>
                <DatePicker picker="month" />
            </Form.Item>
            <Form.Item name="facilityType" label="设备分类:" style={{ marginBottom: '10px' }}>
                <Select
                    style={{ width: "150px" }}
                    options={kindData}
                    placeholder="请选择设备分类"
                />
            </Form.Item>
            <Form.Item name="liftUnit" label="提报单位:">
                <Input placeholder="请输入提报单位" />
            </Form.Item>
            <Form.Item style={{ marginBottom: '10px' }}>
                <Button icon={<SearchOutlined />} type="primary" htmlType="submit" loading={loadings}>查询</Button>
            </Form.Item>
            <Form.Item style={{ marginBottom: '10px' }}>
                <Button icon={<ReloadOutlined />} onClick={() => {
                    form.resetFields();
                }} loading={loadings}>重置</Button>
            </Form.Item>


            <Form.Item style={{ marginBottom: '10px' }}>
                <Button icon={<PlusOutlined />} type="primary" onClick={add}>添加</Button>
            </Form.Item>
            <Form.Item style={{ marginBottom: '10px' }}>
                <Upload {...props}>
                    <Button icon={<CloudUploadOutlined />} type="primary">导入</Button>
                </Upload>
            </Form.Item>
            <Form.Item style={{ marginBottom: '10px' }}>
                <Button icon={<DownloadOutlined />} type="primary" onClick={download}>导入模板下载</Button>
            </Form.Item>
        </Form>
    }


    const getData = () => {
        const values = form.getFieldsValue();
        values['needYearMonth'] = values['needYearMonth'] ? values['needYearMonth'].format('YYYYMM') : ''
        let param = {
            ...values,
            pageSize: pageSizeRef.current,
            pageNum: pageNumRef.current
        }
        setLoadings(true)
        getNeedPlan(param).then((res: any) => {
            setLoadings(false)
            if (res.success) {
                setTableData(res.data.records)
                total.current = res.data.total
            } else {

            }
        })
    }
    const columns: TableColumnsType = [
        {
            title: '序号',
            dataIndex: 'index',
            width: 60,
            align: 'center' as const,
            render: (_text, _record, index) =>
                (pageNumRef.current - 1) * pageSizeRef.current + index + 1,
        },
        {
            title: '需求年月',
            dataIndex: 'needYearMonth',
            width: 100,
        },
        {
            title: '提报单位',
            dataIndex: 'liftUnit',
            // width: 100,
        },
        {
            title: '设备分类',
            dataIndex: 'facilityType',
            width: 150,
        },
        {
            title: '设备码',
            dataIndex: 'facilityCode',
            // width: 100,
        },
        {
            title: '设备码描述',
            dataIndex: 'codeDescribe',
            // width: 100,
        },
        {
            title: '需求提报量(只)',
            dataIndex: 'needLiftNum',
            width: 150,
        },
        {
            title: '增量(只)',
            dataIndex: 'addNum',
            width: 100,
        },
        {
            title: '本月使用量(只)',
            dataIndex: 'monthUseNum',
            width: 150,
        },
        {
            title: '剩余量(只)',
            dataIndex: 'residueNum',
            width: 150,
        },
        {
            title: '操作',
            dataIndex: 'operation',
            fixed: 'right',
            render: (_: any, record) => {
                return <>
                    <Typography.Link onClick={() => edit(record)} style={{ marginRight: 16 }}>
                        编辑
                    </Typography.Link>


                    <Popconfirm
                        title="确定要删除这一行吗？"
                        okText="确认"
                        cancelText="取消"
                        onConfirm={() => handleDelete(record)}
                    >
                        <Typography.Link style={{ color: 'red' }}>删除</Typography.Link>
                    </Popconfirm>
                </>

            },
        },


    ];
    const [visible, setVisible] = useState<boolean>(false);
    const [modalType, setModalType] = useState<'add' | 'edit'>('add');
    const [editRecord, setEditRecord] = useState<any>(null);
    const [id, setId] = useState<number | undefined>(undefined); //编辑id
    const add = () => {
        setModalType('add')
        setVisible(true)
    }
    const edit = (record: any) => {
        setId(record.id)
        setModalType('edit')
        setVisible(true)
        viewMonth({ id: record.id }).then((res: any) => {
            if (res.success) {
                res.data['needYearMonth'] = res.data['needYearMonth'] ? dayjs(res.data['needYearMonth'], 'YYYYMM') : ''
                setEditRecord(res.data)
            } else {
                $message.error(res.message);
            }
        })
    }
    const handleDelete = (record: any) => {
        deleteMonth({ ids: record.id }).then((res: any) => {
            if (res.success) {
                $message.success('删除成功');
                getData()
            } else {
                $message.error(res.message);
            }
        })
    }
    const cancel = () => {
        setVisible(false)
    }
    const submit = (obj: any) => {
        if (modalType == 'add') {
            addMonth(obj).then((res: any) => {
                if (res.success) {
                    $message.success('添加成功');
                    setVisible(false)
                    getData()
                } else {
                    $message.error(res.message);
                }
            })
        } else {
            obj['id'] = id
            updateMonth(obj).then((res: any) => {
                if (res.success) {
                    $message.success('编辑成功');
                    setVisible(false)
                    getData()
                } else {
                    $message.error(res.message);
                }
            })
        }
    }
    const getTable = () => {
        return <Table
            columns={columns}
            dataSource={tableData}
            scroll={{ x: 'max-content' }}
            pagination={false}
            sticky={true}
            style={{ height: '90%', overflowY: 'auto', overflowX: 'hidden' }}
            rowKey="id"
        />
    }
    const total = useRef(0);
    const pageNumRef = useRef(1);
    const pageSizeRef = useRef(10);
    const [current, setCurrent] = useState<number>(1);
    const onChange: PaginationProps['onChange'] = (page, pageSize) => {
        pageNumRef.current = page;
        pageSizeRef.current = pageSize;
        setCurrent(page)
        getData()
    }
    const getPagination = () => {
        return <> <Pagination
            size="small"
            total={total.current}
            showSizeChanger
            showQuickJumper
            showTotal={(total) => `共 ${total} 条`}
            onChange={onChange}
            current={current}
        />
            <AddEdit visible={visible} cancel={cancel}
                submit={submit} type={modalType}
                initialValues={editRecord}
            ></AddEdit>
        </>

    }


    return <>
        <Common top={getTop()} table={getTable()} paginations={getPagination()} />
    </>
}

export default Month